/*
 * @Author: ReinerLau lk850593913@gmail.com
 * @Date: 2023-02-16 13:48:00
 * @LastEditors: ReinerLau lk850593913@gmail.com
 * @LastEditTime: 2023-02-16 15:26:08
 * @FilePath: \v2.0.0\src\views\patroling\composables\useNotify.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { ElNotification, ElMessage } from "element-plus";
import { ComputedRef, h, onBeforeUnmount, ref, Ref } from "vue";
import { websocketData } from "../shared";
import usePatrolingStore from "@/store/patroling";
interface Options {
  notificationTypeMap: ComputedRef<{
    title: string;
    baseColor: string;
    color: string;
  }>;
  notificationType: Ref<string>;
}
export default (options: Options) => {
  const { notificationTypeMap, notificationType } = options;
  const alarmRef: Ref<HTMLAudioElement> = ref(null);
  let isShowNotification = false;
  const msgVNode = (id: string, message: string) =>
    h(
      "div",
      {
        class: "message-container",
      },
      [
        h(
          "div",
          {
            class: "message-type",
          },
          notificationTypeMap.value.title
        ),
        h(
          "div",
          {
            class: "message-content",
          },
          `${id} ${message}`
        ),
      ]
    );
  const patrolingStore = usePatrolingStore();
  const { addNotification } = patrolingStore;
  function handleNotification(e) {
    const data: websocketData = JSON.parse(e.data);
    const { type, id, message } = data;
    if (data.type !== "normal") {
      alarmRef.value && alarmRef.value.play();
    }
    if (!isShowNotification) {
      notificationType.value = type;
      ElNotification({
        message: msgVNode(id, message),
        position: "bottom-right",
        offset: 85,
        duration: 0,
        onClose() {
          isShowNotification = false;
        },
        appendTo: "#bottom",
      });
      isShowNotification = true;
    }
    addNotification(data);
  }
  let wsStatusNotification;
  function handleWsOpen(e, { reconnectWebsocketSt }) {
    clearTimeout(reconnectWebsocketSt.value);
    if (wsStatusNotification) {
      wsStatusNotification.close();
    }
    ElMessage({
      type: "success",
      message: "连接成功",
    });
  }
  function handleWsClose(e, { reconnectWebsocket }) {
    if (wsStatusNotification) {
      wsStatusNotification.close();
    }
    wsStatusNotification = ElMessage({
      type: "error",
      message: "连接断开,尝试重连...",
      duration: 0,
    });
    reconnectWebsocket();
  }

  onBeforeUnmount(() => {
    if (wsStatusNotification) {
      wsStatusNotification.close();
    }
  });

  return {
    handleNotification,
    alarmRef,
    handleWsClose,
    handleWsOpen,
  };
};
